package cn.myfirefly.moming.portal.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.myfirefly.moming.common.model.MenuResultDto;
import cn.myfirefly.moming.portal.entity.MMSystemAccess;
import cn.myfirefly.moming.portal.model.RoleManageSearchDto;
import cn.myfirefly.moming.portal.model.WebOsDto;
import cn.myfirefly.moming.portal.service.FunctionService;
import cn.myfirefly.moming.portal.service.LoginService;
import cn.myfirefly.moming.portal.service.RoleService;
import cn.myfirefly.moming.portal.service.SystemAccessService;
import cn.myfirefly.moming.portal.service.UserBackgroundService;
import cn.myfirefly.moming.portal.service.UserSysService;
import cn.myfirefly.core.BaseController;
import cn.myfirefly.core.Const;
import cn.myfirefly.core.model.Identity;
import cn.myfirefly.core.model.LoginDto;
import cn.myfirefly.core.model.ResultDto;
import cn.myfirefly.utils.CollectionUtil;
import cn.myfirefly.utils.Prop;
import cn.myfirefly.utils.PropUtil;

@Controller
public class IndexController extends BaseController {
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private SystemAccessService systemAccessService;
	
	@Autowired
	private UserSysService userSysService;
	
	@Autowired
	private UserBackgroundService userBackgroundService;
	
	@Autowired
	private FunctionService functionService;
	
	@Autowired
	private LoginService loginService;
	
	@RequestMapping(value = "/logout.do")
	public String logout(HttpServletRequest request,
			HttpServletResponse response) {
		Prop configProp = PropUtil.use("config.properties");
		//清除session
		request.getSession().removeAttribute("identity");
		request.getSession().setAttribute("_const_cas_assertion_", null);
		//清除cookie
		Cookie[] cookies = request.getCookies();
		 for(int i = 0,len = cookies.length; i < len; i++) {
			Cookie cookie = new Cookie(cookies[i].getName(),null);
            cookie.setMaxAge(0);
            cookie.setPath("/");
            response.addCookie(cookie);
		}
		
		//重定向到单点登陆的登录页面
		return "redirect:"+ configProp.get("ssoLogoutUrl")+"?service="+configProp.get("clientLogoutUrl");
	}
	
	@RequestMapping(value = "/main.do")
	public String toMain(HttpServletRequest request,
			HttpServletResponse response) {
		return "index";
	}
	
	@RequestMapping(value = "/initTableMenu.do")
	@ResponseBody
	public Map<String, Map<String, WebOsDto>> initTableMenu(HttpServletRequest request){
		//通过登录者信息 获取可以操作的系统信息,系统需处于启用状态
		//根据登陆者信息 获取角色信息
		Identity identity = (Identity) request.getSession().getAttribute("identity");
		List<MMSystemAccess> list = null;
		if (identity.isAdmin()) {
			// 如果是超级管理员，则取得所有系统模块
			list = systemAccessService.getSystemAccessList(false);
		} else {
			List<RoleManageSearchDto> roleList = roleService.getRolesByLoginName(identity.getLoginName());
			String in = "";
			if(roleList != null && roleList.size() > 0){
				int index = 0;
				for (int i = 0; i < roleList.size(); i++) {
					if(index == (roleList.size() - 1)){
						in += roleList.get(i).getRoleSn();
						break;
					}
					in += roleList.get(i).getRoleSn()+",";
					index ++;
				}
			}
			//根据角色获取 登陆者拥有的 系统菜单权限 , 系统必须处于启用状态
			list = systemAccessService.getSystemAccessListByRoleSn(in);
		}
		//从用户与快捷栏关联表中查询出菜单的id列表
		List<Integer> sysIds = systemAccessService.getSysIdsByUserSn(identity.getUserSn());
		//定义两个list 一个为常规菜单 一个为快捷栏菜单
		Map<String,WebOsDto> center = new HashMap<String, WebOsDto>();
		Map<String,WebOsDto> left = new HashMap<String, WebOsDto>();
		WebOsDto dto = null;
		if(CollectionUtil.isNotEmpty(list)){
			for(MMSystemAccess l : list){
				dto = new WebOsDto();
				dto.setAppid(l.getSystemAccessId());
				dto.setAsc(l.getSystemAccessId());
				dto.setIcon(l.getIconSmall());
				dto.setName(l.getSystemName() == null?"名称":l.getSystemName());
				if (l.getAccessUrl().indexOf("?") >= 0) {
					dto.setUrl(l.getAccessUrl() + "&systemId=" + l.getSystemId());
				} else {
					dto.setUrl(l.getAccessUrl() + "?systemId=" + l.getSystemId());
				}
				dto.setWidth(l.getWidth());
				dto.setHeight(l.getHeight());
				if(sysIds.contains(l.getSystemAccessId())){
					left.put(l.getSystemAccessId()+"",dto);
				}else{
					center.put(l.getSystemAccessId()+"",dto);
				}
			}
		}
		//将结果集 添加到 map中 方法返回map
		Map<String, Map<String,WebOsDto>> map = new HashMap<String, Map<String,WebOsDto>>();
		map.put("app", center);
		map.put("sApp", left);
		
		return map;
	}
	
	@RequestMapping(value = "/changeItem.do")
	@ResponseBody
	public ResultDto changeItem(HttpServletRequest request){
		Identity identity = (Identity) request.getSession().getAttribute("identity");
		try {
			String type = request.getParameter("type");
			String sysId = request.getParameter("sysId");
			if("insert".equals(type)){
				//增加
				userSysService.save(sysId, identity.getUserSn());
			}else if("delete".equals(type)){
				//删除
				userSysService.delete(sysId, identity.getUserSn());
			}else{
				return error("参数有误");
			}
			
		} catch (Exception e) {
			return error(e.getMessage());
		}
		return success();
	}
	
	@RequestMapping(value = "/getBackGroudPic.do")
	@ResponseBody
	public ResultDto getBackGroudPic(HttpServletRequest request){
		try {
			Identity identity = (Identity) request.getSession().getAttribute("identity");
			return success(userBackgroundService.getBackgroundPicByUserSn(identity.getUserSn()));
		} catch (Exception e) {
			return error(e.getMessage());
		}
	}
	
	@RequestMapping(value = "/saveBackGroudPic.do")
	@ResponseBody
	public ResultDto saveBackGroudPic(HttpServletRequest request){
		ResultDto result = null;
		try {
			String picName = request.getParameter("pic"); 
			Identity identity = (Identity) request.getSession().getAttribute("identity");
			userBackgroundService.saveBackGroudPic(identity, picName);
			result = success("保存成功");
		} catch (Exception e) {
			result = error(e.getMessage());
		}
		return result;
	}
	
	@RequestMapping(value = "/systemConfig.do")
	public String systemConfig(HttpServletRequest request,
			HttpServletResponse response) {
		//通过登陆者信息 初始化 菜单
		Identity identity = (Identity)request.getSession().getAttribute("identity");
		List<MenuResultDto> list = null;
		if (identity.isAdmin()) {
			list = functionService.getMenus(1);
		} else {
			list = functionService.getMenus(identity.getLoginName(), 1);
		}
		request.setAttribute("menus", list);
		return "main";
	}
	
	@RequestMapping("/myhome.do")
	public String welcome(HttpServletRequest request, 
			HttpServletResponse response) {
		
		return "myhome";
	}
	
	@RequestMapping("/changePasswd/index.do")
	public String changePwd(HttpServletRequest request, 
			HttpServletResponse response) {
		return "changePwd";
	}
	
	@RequestMapping("/changePasswd/update.do")
	@ResponseBody
	public ResultDto saveNewPwd(LoginDto dto, HttpServletRequest request, 
			HttpServletResponse response) {
		dto.setLoginName(getLoginUser(request).getLoginName());
		String msg = loginService.savePwd(dto);
		if (!Const.ResultCode.SUCCESS.equals(msg)) {
			return error(msg);
		}
		return success("修改成功");
	}
	
	@RequestMapping(value="/getUserInfo.do")
	@ResponseBody
	private ResultDto getUserInfo(){
		return success();
	}
}
